﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace wcfServiceLib
{
    class StandardRepository<T> : IRepository<T> where T : class 
    {
        protected DbContext DBContext { get; set; }
        protected DbSet<T> DBSet { get; set; }

        public StandardRepository(DbContext dbContext)
        {
            DBContext = dbContext;
            DBSet = DBContext.Set<T>();
        }

        public virtual IQueryable<T> GetAll()
        {
            return DBSet;
        }

        public virtual T GetById(int id)
        {
           return DBSet.Find(id);
        }

        public virtual void Add(T entity)
        {
            var dbEntry = DBContext.Entry(entity);
            if (dbEntry.State != EntityState.Detached)
            {
                dbEntry.State = EntityState.Added;
            }
            else
            {
                DBSet.Add(entity);
            }
        }

        public virtual void Update(T entity)
        {
            var dbEntry = DBContext.Entry(entity);
            if (dbEntry.State == EntityState.Detached)
            {
                DBSet.Attach(entity);
            }
            dbEntry.State = EntityState.Modified;     
        }

        public virtual void Delete(T entity)
        {
            var dbEntry = DBContext.Entry(entity);
            if (dbEntry.State != EntityState.Deleted)
            {
                dbEntry.State = EntityState.Deleted;
            }
            else
            {
                DBSet.Attach(entity);
                DBSet.Remove(entity);
            }
        }

        public virtual void Delete(int id)
        {
            var item = GetById(id);
            if (item == null)
            {
                return;
            }
            Delete(item);
        }



    }
}
